package com.example.userserver.controller;

import cn.hutool.core.util.IdUtil;
import com.example.userserver.enums.ReturnEnum;
import com.example.userserver.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@RestController
public class PhotosController {// 图片上传
    @Value("${photo.update}")
    private String localPath;
    @Value("${server.ip}")
    private String serverIp;
    @PostMapping("/upload")

    public Result fileUpload(MultipartFile file, HttpServletRequest request){
        // 图片上传服务器后所在的文件夹
        String realPath =  localPath;
        File folder = new File(realPath);
        if(!folder.exists())
            folder.mkdirs();
        // 修改图片的名字（防止重复）
        String oldName = file.getOriginalFilename();
        IdUtil idUtil = new IdUtil();
        String newName = idUtil.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
        try {
            // 将文件放到目标文件夹
            file.transferTo(new File(folder, newName));
            // 通常还需要返回图片的URL，为了通用性，需要动态获取协议，不要固定写死
            String returnUrl = serverIp + newName;
            return new Result(returnUrl, ReturnEnum.SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
